package com.lizardmind.haofudoctor.ui.diagnosis.sickMan.advisory.kaifang

import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.View
import com.linxiao.framework.activity.BaseActivity
import com.linxiao.framework.adapter.BaseAdapter
import com.linxiao.framework.util.getDataBinding
import com.linxiao.framework.util.ke
import com.linxiao.framework.util.toasts
import com.lizardmind.haofudoctor.R
import com.lizardmind.haofudoctor.databinding.ActivityKaiFangSureBinding
import com.lizardmind.haofudoctor.databinding.ItemTextOnlyBinding
import com.lizardmind.haofudoctor.manager.postApi
import com.lizardmind.haofudoctor.other.*
import com.lizardmind.haofudoctor.other.rongYun.FanganTipsMessage
import com.lizardmind.haofudoctor.other.rongYun.HaofuMessage
import com.lizardmind.haofudoctor.other.rongYun.MessageTags
import com.lizardmind.haofudoctor.other.rongYun.USER_PREFIX
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import kotlinx.android.synthetic.main.activity_kai_fang_sure.*
import kotlinx.android.synthetic.main.include_title_text.*
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

/**
 * 开方确认activity
 */
class KaiFangSureActivity : BaseActivity() {

    private lateinit var jsonData:String
    private lateinit var js:JSONObject

    private val listChuFang= arrayListOf<String>()

    private val dataBing by lazy { getDataBinding<ActivityKaiFangSureBinding>(R.layout.activity_kai_fang_sure) }
    private val adapterChuFang by lazy { BaseAdapter<String, ItemTextOnlyBinding>(R.layout.item_text_only,listChuFang) }
    override fun onCreatRootView(): View? {
       return dataBing.root
    }

    override fun onInitView(savedInstanceState: Bundle?) {
        val bundle= intent.getBundleExtra("kf_bundle")
        jsonData=bundle.getString("jsonData")

        titleText.text="确认方案"
        imgLeft.setImageResource(R.mipmap.back)
        imgLeft.onClick { finish() }

        js=JSONObject(jsonData)
        tvSickManData.text=bundle.getString("sickManData")+"岁"
        tvDiseaseName.text=js.getString("symptoms")
        tvKaiFangTime.text=SimpleDateFormat("yyyy-MM-dd HH:mm").format(Date())
        tvTakeWayNum.text=js.getString("number")
        val takeWay=js.getString("fufa").split("~")
        tvTakeWay.text="每日"+takeWay[0]+"帖 一帖分"+takeWay[1]+"次服用"
        tvEatTime.text=js.getString("fu_time")
        var raboo=js.getString("avoid")
        if (raboo.isEmpty()){ raboo="无" }
        tvTaboo.text=if(raboo.startsWith("无")&&raboo.length>3){
            raboo.substring(2,raboo.length)
        }else{
            if (raboo.endsWith("，")) raboo.substring(0,raboo.length-1) else raboo
        }
        tvThinking.text=js.getString("way")

        val list=js.getString("prescription").split("，")
        for (i in 0 until list.size){
            listChuFang.add(list[i])
        }
        rvChuFang.layoutManager= GridLayoutManager(this,2)
        rvChuFang.adapter=adapterChuFang

        tvKaiFangPostNow.onClick {
            postKaiFang()
        }

    }

    private fun postKaiFang(){
        observe {
            postApi<Request<String>>(hashMapOf(
                    "action" to "add_prescribing",
                    "token" to DoctorInfo.token,
                    "data" to jsonData.replace("\"","\\\"")
            ), Consumer {
                it.dispose {
                    RongIM.getInstance().sendMessage(
                            Message.obtain(USER_PREFIX +JSONObject(jsonData).getString("uid"), Conversation.ConversationType.PRIVATE, HaofuMessage(jsonOf("id" to it,"type" to "1"))),
                            MessageTags.HAOFU,
                            null,
                            object : io.rong.imlib.IRongCallback.ISendMessageCallback {
                                override fun onAttached(p0: Message) {}
                                override fun onSuccess(p0: Message) {
                                    //消息通过网络发送成功的回调
                                    RongIM.getInstance().sendMessage(
                                            Message.obtain(USER_PREFIX+JSONObject(jsonData).getString("uid"), Conversation.ConversationType.PRIVATE, FanganTipsMessage(jsonOf("id" to it,"endTime" to "1"))),
                                            MessageTags.FANGAN_TIPS,
                                            null,
                                            object : io.rong.imlib.IRongCallback.ISendMessageCallback {
                                                override fun onAttached(p0: Message) {}
                                                override fun onSuccess(p0: Message) {
                                                    toasts("发送成功")
                                                    EventBus.getDefault().post(KaiFangFinishEvent())
                                                    finish()
                                                }
                                                override fun onError(p0: Message?, p1: RongIMClient.ErrorCode) {}
                                            }
                                    )
                                }
                                override fun onError(p0: Message?, p1: RongIMClient.ErrorCode) {}
                            }
                    )
                }

            }, Action {

            },context = this)
        }
    }

}
